<?php

namespace app\admin\model;

use app\common\enums\StatusEnum;
use think\Db;

class Coupon extends \app\common\model\Coupon
{
    /**
     * 列表
     * @param $where
     * @param $oauthId
     * @param $type
     * @return array
     * @throws \think\exception\DbException
     */
    public static function getList($where, $oauthId = 0, $type = 0)
    {
        $sql = static::field('id, name, money, start_time, end_time, rule, sort_num, status, create_time, update_time');

        if ($where) {
            $sql->where($where);
        }

        $time = time();

        $data = $sql->paginate(null, false, ['query' => request()->param()]);

        $couponIds = [];
        foreach ($data->items() as $key => $value) {
            $couponIds[$value['id']] = $value['id'];
        }

        $useCount = [];
        if ($couponIds) {
            $useCount = CouponUsed::getColumnByCoupon($couponIds);
        }

        $used = [];
        $inIds = [];
        if ($oauthId > 0) {
            // 使用状态
            $used = CouponUsed::getColumn($oauthId);
        }

        if ($oauthId > 0 && $type != -1 && $type != null) {
            // 获取所有优惠券
            $all = self::getColumnEnd();
            foreach ($all as $couponId => $endTime) {
                if (isset($used[$couponId])) {
                    $useType = self::USED;
                } else if ($endTime < $time) {
                    $useType = self::EXPIRED;
                } else {
                    $useType = self::NO_USE;
                }

                // 使用状态搜索
                if ($type == $useType) {
                    $inIds[] = $couponId;
                }
            }

            // 重新赋值data
            $data = $sql->where('id', 'in', $inIds)->paginate(null, false, ['query' => request()->param()]);
        }

        $model = $data->each(function ($item, $key) use ($oauthId, $used, $time, $useCount) {
            if ($oauthId > 0) {
                // 使用状态
                if (isset($used[$item['id']])) {
                    $item['use_status'] = '已使用';
                    $item['order_sn'] = $used[$item['id']]['order_sn'];
                    $item['use_time'] = get_datetime($used[$item['id']]['create_time']);
                } else if ($item['end_time'] < $time) {
                    $item['use_status'] = '已过期';
                    $item['order_sn'] = '暂无';
                    $item['use_time'] = '/';
                } else {
                    $item['use_status'] = '未使用';
                    $item['order_sn'] = '暂无';
                    $item['use_time'] = '/';
                }
            }

            $item['useCount'] = isset($useCount[$item['id']]) ? $useCount[$item['id']] : 0;
            $item['create_time'] = get_datetime($item['create_time']);
            $item['start_time'] = get_datetime($item['start_time']);
            $item['end_time'] = get_datetime($item['end_time']);
            $item['update_time'] = get_datetime($item['update_time']);
            $item['statusText'] = StatusEnum::getStatus($item['status']);
            return $item;
        });

        // 获取总记录数
        $count = $model->total();
        return [
            'model' => $model,
            'count' => $count
        ];
    }

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getColumn()
    {
        $model = static::field('id, name')
            ->where(['status' => StatusEnum::ENABLED])
            ->select()->toArray();
        $result = [];
        foreach ($model as $key => $value) {
            $result[$value['id']] = $value['name'];
        }
        return $result;
    }

    /**
     * id => end_time
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getColumnEnd()
    {
        $model = static::field('id, end_time')->select()->toArray();
        $result = [];
        foreach ($model as $key => $value) {
            $result[$value['id']] = $value['end_time'];
        }
        return $result;
    }

    /**
     * 删除
     * @param $id
     */
    public static function deleteOne($id)
    {
        $model = static::get($id);
        if ($model) {
            $model->delete();
        }
    }

    /**
     * 修改状态
     * @param $id
     */
    public static function disabledOne($id)
    {
        $model = static::get($id);
        if ($model) {
            $model->status = ($model->status == StatusEnum::ENABLED) ? StatusEnum::DISABLED : StatusEnum::ENABLED;
            $model->update_time = time();
            $model->save();
        }
    }

    /**
     * 批量禁用启用
     * @param $ids
     * @param $status
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function disables($ids, $status)
    {
        static::where('id', 'in', $ids)->update(['status' => $status]);
    }

    /**
     * 添加修改
     * @param $data
     * @return int|string
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function saveOne($data)
    {
        $saveData = [
            'name' => $data['name'],
            'money' => $data['money'],
            'start_time' => strtotime($data['start_time']),
            'end_time' => strtotime($data['end_time']),
            'rule' => $data['rule'],
            'sort_num' => $data['sort_num'],
            'status' => $data['status'],
            'update_time' => time()
        ];

        if (isset($data['id']) && $data['id'] > 0) {
            Db::name('coupon')
                ->where('id', $data['id'])
                ->data($saveData)
                ->update();
            $id = $data['id'];
        } else {
            $saveData['create_time'] = time();
            $id = Db::name('coupon')->insertGetId($saveData);
        }
        return $id;
    }
}